import React, { useRef, useEffect, memo, useState } from 'react';
import { Row, Col, Input, Button, Table } from 'antd';
import styles from './index.less';
import useModel from '../../useModels/useModel.js';
import EmptyCenter from '@/components/EmptyCenter';
import offset from 'document-offset';
import classnames from 'classnames';
import Connect from '@/components/Connect';
import moment from 'moment';
import DetailModal from './detailModal.jsx';
import { useSize, useAntdTable, useUpdateEffect } from '@umijs/hooks';
import { getLog } from '../../service';
const { Search } = Input;

const ContextMenu = Connect(state => {
  return {
    contextMenuPosition: state.contextMenuPosition,
    contextMenuVisible: state.contextMenuVisible,
  };
}, useModel)(
  memo(props => {
    const { setState, contextMenuPosition, contextMenuVisible, setHistoryMessage } = props;
    return (
      <ul
        className={styles['context-menu']}
        style={{
          left: contextMenuPosition.left,
          display: contextMenuVisible ? 'block' : 'none',
          top: contextMenuPosition.top,
        }}
      >
        <li
          onClick={e => {
            e.stopPropagation();
            setState({ contextMenuVisible: false });
            setHistoryMessage([]);
          }}
        >
          清空
        </li>{' '}
        setHistoryMessage,
      </ul>
    );
  }),
);

export default Connect(state => {
  return {
    historyMessage: state.historyMessage,
    singleData: state.singleData,
    keyword: state.keyword,
  };
}, useModel)(
  memo(props => {
    const { setState, singleData, historyMessage, keyword } = props;
    const [size, ref] = useSize();

    // const list = historyMessage.filter(item => {
    //   return (item.customName || '').includes(keyword);
    // });
    return (
      <div className={styles['wrap']}>
        <div className={styles['header-wrap']}>
          <span className={styles['title']}>
            <span style={{ color: '#00a0e9' }}>{singleData.suId}</span>
            <span> 报文结果</span>
          </span>
          <span className={styles['search-wrap']}>
            <Search
              placeholder={'请输入搜索内容'}
              onSearch={value => setState({ keyword: value })}
            />
          </span>
          <span className={styles['remark']}>点击指令下发报文查看报文详情</span>
        </div>
        <div
          className={styles['result-wrap']}
          ref={ref}
          onClick={() => {
            setState({
              contextMenuVisible: false,
            });
          }}
          // onContextMenu={e => {
          //   e.preventDefault();
          //   let fix = offset(ref.current);
          //   let scrollTop = ref.current.scrollTop;
          //   setState({
          //     contextMenuPosition: {
          //       left: event.clientX - fix.left,
          //       top: event.clientY - fix.top + scrollTop,
          //     },
          //     contextMenuVisible: true,
          //   });
          // }}
        >
          {/* <ContextMenu /> */}
          <InstructionTable
            size={size}
            keyword={keyword}
            singleData={singleData}
            setState={setState}
          />
        </div>
        <DetailModal />
      </div>
    );
  }),
);
const InstructionTable = ({ singleData, keyword, size, setState: dispatch }) => {
  const [state, setState] = useState({
    filteredInfo: null,
    sortedInfo: null,
  });
  const columns = [
    {
      title: '报文名称',
      align: 'center',
      dataIndex: 'customName',
      key: 'customName',
    },
    {
      title: '报文类型',
      align: 'center',
      dataIndex: 'customType',
      key: 'customType',
      filterMultiple: false,
      filters: [
        { text: 'SU-SC 被动', value: 0 },
        { text: 'SC-SU 主动', value: 1 },
      ],

      render: (text, row, index) => {
        let type = {
          0: 'SU-SC 被动',
          1: 'SC-SU 主动',
        };
        return <>{type[text]}</>;
      },
    },
    {
      title: '报文结果',
      align: 'center',
      dataIndex: 'result',
      render: (text, row, index) => {
        let type = {
          0: '失败',
          1: '成功',
        };
        return <>{type[text]}</>;
      },
    },
    {
      title: '时间',
      align: 'center',
      dataIndex: 'time',
      sorter: true,
      key: 'time',
      render: (text, row, index) => {
        return <>{text ? moment(text).format('YYYY-MM-DD  HH:mm:ss') : '-'}</>;
      },
    },
  ];
  const handleChange = (pagination, filters, sorter) => {
    setState(prevState => ({
      ...prevState,
      filteredInfo: filters,
      sortedInfo: sorter,
    }));
  };
  const paddingTop = 25;
  const paddingBottom = 16;
  const headerHeight = 46;
  let scroll = size.height
    ? { scroll: { y: size.height - headerHeight - paddingTop - paddingBottom } }
    : {};
  //获取日志列表
  const getTableData = ({ current, pageSize, sorter, filters }) => {
    let obj = {};
    if (filters) {
      Object.entries(filters).forEach(item => {
        if (item[1]) {
          obj[item[0]] = item[1].join(',');
        }
      });
    }

    return getLog({
      ...obj,
      sort: sorter?.order || undefined,
      sortField: sorter?.order ? sorter.field : undefined,
      customName: keyword,
      currentPage: current,
      pageSize,
      suIndex: singleData.id,
    }).then(res => {
      return {
        total: res?.data?.totalCount || null,
        data: res?.data?.dataList || [],
      };
    });
  };
  const { refresh, tableProps, filters, sorter } = useAntdTable(getTableData, {
    defaultPageSize: 10,
  });

  useUpdateEffect(() => {
    refresh();
  }, [keyword]);
  return (
    <Table
      className={classnames(styles['table-wrap'], styles['alarm-height'])}
      columns={columns}
      onChange={handleChange}
      {...scroll}
      locale={{
        filterConfirm: '确定',
        filterReset: '重置',
      }}
      rowKey="id"
      onRow={record => {
        return {
          onClick: event => {
            dispatch({ messageDetailVisible: true, messageDetailItem: record });
          },
        };
      }}
      {...tableProps}
      pagination={{
        ...tableProps.pagination,
        showTotal: total => `共 ${tableProps.pagination.total || 0} 条`,
        showQuickJumper: true,
        showSizeChanger: true,
      }}
    />
  );
};
